﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NTQOnlineExam.Services.EntityFW.Entity;
using NTQOnlineExam.Services.EntityFW.Repository;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Infrastructure.Utility;
using NTQOnlineExam.Services.Models;
using NTQOnlineExam.Services.ReportService.Order;

namespace NTQOnlineExam.Services.CommandService
{
  public class PortfolioCommandService : IPortfolioCommandService
  {
    private readonly IUnitOfWork _unitOfWork;
    private readonly ICommandExecutor _commandExecutor;
    public PortfolioCommandService(IUnitOfWork unitOfWork, ICommandExecutor commandExecutor)
    {
      _unitOfWork = unitOfWork;
      _commandExecutor = commandExecutor;
    }

    public void InsertPortfolioFromOrder(Order order)
    {
      try
      {
        _unitOfWork.BeginTransaction();
        //Update user's portfolio
        var portfoliItem = InitUserPortfolioItems(order);
        foreach (var portfolio in portfoliItem)
        {
          _unitOfWork.Repository<Portfolio>().Insert(portfolio);
        }
        _unitOfWork.Save();
        _unitOfWork.Commit();
      }
      catch (Exception ex)
      {
        _unitOfWork.Rollback();
        throw new Exception(ex.Message, ex);
      }
    }

    private IEnumerable<Portfolio> InitUserPortfolioItems(Order order)
    {
      int termExpiredDays = ValueUtilities.GetInt32(ConfigurationManager.AppSettings["TermExpiredDays"], 21);
      var newPortfolioItems = new List<Portfolio>();
      var orderDetails = _commandExecutor.Execute(new GetOrderDetailByOrderIdDbCommand(order.OrderId));
      if (orderDetails == null || !orderDetails.Any()) return new List<Portfolio>();
      foreach (var orderDetail in orderDetails)
      {
        newPortfolioItems.Add(new Portfolio
        {
          ExpiredDate = order.CreationDate.AddDays(termExpiredDays),
          OrderDate = order.CreationDate,
          PortfolioId = Guid.NewGuid(),
          OrderId = order.OrderId,
          TermId = orderDetail.TermId,
          TermName = orderDetail.TermName,
          UserId = order.UserId
        });
      }
      return newPortfolioItems;
    }
  }
}
